#include "orderstatisticswidget.h"
#include "errorhandler.h"

const QString OrderStatisticsWidget::STAT_ITEM_STYLE = R"(
    QWidget {
        background-color: white;
        border: 1px solid #E0E0E0;
        border-radius: 4px;
        padding: 4px;
    }
    QLabel {
        border: none;
        padding: 2px;
        font-size: 10px;
    }
)";

const QString OrderStatisticsWidget::PROGRESS_STYLE = R"(
    QProgressBar {
        border: 1px solid #D0D0D0;
        border-radius: 3px;
        text-align: center;
        font-size: 10px;
        background-color: #F5F5F5;
    }
    QProgressBar::chunk {
        background-color: #4CAF50;
        border-radius: 2px;
    }
)";

OrderStatisticsWidget::OrderStatisticsWidget(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_statsContainer(nullptr)
    , m_statsLayout(nullptr)
    , m_totalOrdersItem(nullptr)
    , m_totalOrdersValue(nullptr)
    , m_pendingOrdersItem(nullptr)
    , m_pendingOrdersValue(nullptr)
    , m_preparingOrdersItem(nullptr)
    , m_preparingOrdersValue(nullptr)
    , m_completedOrdersItem(nullptr)
    , m_completedOrdersValue(nullptr)
    , m_cancelledOrdersItem(nullptr)
    , m_cancelledOrdersValue(nullptr)
    , m_revenueItem(nullptr)
    , m_revenueValue(nullptr)
    , m_avgOrderValueItem(nullptr)
    , m_avgOrderValueValue(nullptr)
    , m_progressContainer(nullptr)
    , m_progressLayout(nullptr)
    , m_progressLabel(nullptr)
    , m_completionProgressBar(nullptr)
    , m_separatorLine(nullptr)
    , m_todayFocus(true)
    , m_animationTimer(nullptr)
    , m_animationStep(0)
    , m_targetProgress(0)
    , m_currentProgress(0)
{
    // 创建动画定时器
    m_animationTimer = new QTimer(this);
    m_animationTimer->setInterval(50); // 50ms间隔
    
    setupLayout();
    setupLabels();
    
    // 连接动画定时器
    connect(m_animationTimer, &QTimer::timeout, [this]() {
        if (m_currentProgress != m_targetProgress) {
            // 根据方向调整进度
            if (m_currentProgress < m_targetProgress) {
                m_currentProgress = qMin(m_targetProgress, m_currentProgress + 2);
            } else {
                m_currentProgress = qMax(m_targetProgress, m_currentProgress - 2);
            }
            m_completionProgressBar->setValue(m_currentProgress);
        } else {
            m_animationTimer->stop();
        }
    });
}

OrderStatisticsWidget::~OrderStatisticsWidget()
{
    // Qt会自动清理子对象
}

void OrderStatisticsWidget::updateStatistics(const OrderStatistics& stats)
{
    m_currentStats = stats;
    updateLabels(stats);
}

void OrderStatisticsWidget::setTodayFocus(bool enabled)
{
    m_todayFocus = enabled;
    
    if (m_progressLabel) {
        if (enabled) {
            m_progressLabel->setText("今日完成率:");
        } else {
            m_progressLabel->setText("总体完成率:");
        }
    }
}

void OrderStatisticsWidget::setupLayout()
{
    // 创建主布局
    m_mainLayout = new QHBoxLayout(this);
    m_mainLayout->setContentsMargins(8, 4, 8, 4);
    m_mainLayout->setSpacing(8);
    
    // 创建统计项容器
    m_statsContainer = new QWidget();
    m_statsLayout = new QHBoxLayout(m_statsContainer);
    m_statsLayout->setContentsMargins(0, 0, 0, 0);
    m_statsLayout->setSpacing(6);
    
    // 创建分隔线
    m_separatorLine = new QFrame();
    m_separatorLine->setFrameShape(QFrame::VLine);
    m_separatorLine->setFrameShadow(QFrame::Sunken);
    m_separatorLine->setStyleSheet("color: #D0D0D0;");
    
    // 创建进度条容器
    m_progressContainer = new QWidget();
    m_progressContainer->setFixedWidth(150);
    m_progressLayout = new QVBoxLayout(m_progressContainer);
    m_progressLayout->setContentsMargins(4, 0, 4, 0);
    m_progressLayout->setSpacing(2);
    
    m_progressLabel = new QLabel("今日完成率:");
    m_progressLabel->setStyleSheet("font-size: 10px; color: #666666;");
    
    m_completionProgressBar = new QProgressBar();
    m_completionProgressBar->setRange(0, 100);
    m_completionProgressBar->setValue(0);
    m_completionProgressBar->setFixedHeight(16);
    m_completionProgressBar->setStyleSheet(PROGRESS_STYLE);
    
    m_progressLayout->addWidget(m_progressLabel);
    m_progressLayout->addWidget(m_completionProgressBar);
    
    // 添加到主布局
    m_mainLayout->addWidget(m_statsContainer);
    m_mainLayout->addWidget(m_separatorLine);
    m_mainLayout->addWidget(m_progressContainer);
    m_mainLayout->addStretch();
    
    // 设置整体样式
    setStyleSheet(R"(
        OrderStatisticsWidget {
            background-color: #F8F9FA;
            border-top: 1px solid #E0E0E0;
            font-family: 'Microsoft YaHei', sans-serif;
        }
    )");
}

void OrderStatisticsWidget::setupLabels()
{
    // 创建统计项
    m_totalOrdersItem = createStatItem("总订单", "0", "#2196F3");
    m_pendingOrdersItem = createStatItem("待处理", "0", "#FF9800");
    m_preparingOrdersItem = createStatItem("制作中", "0", "#2196F3");
    m_completedOrdersItem = createStatItem("已完成", "0", "#4CAF50");
    m_cancelledOrdersItem = createStatItem("已取消", "0", "#F44336");
    m_revenueItem = createStatItem("营业额", "¥0.00", "#FF5722");
    m_avgOrderValueItem = createStatItem("平均单价", "¥0.00", "#9C27B0");
    
    // 获取值标签的引用
    m_totalOrdersValue = m_totalOrdersItem->findChild<QLabel*>("valueLabel");
    m_pendingOrdersValue = m_pendingOrdersItem->findChild<QLabel*>("valueLabel");
    m_preparingOrdersValue = m_preparingOrdersItem->findChild<QLabel*>("valueLabel");
    m_completedOrdersValue = m_completedOrdersItem->findChild<QLabel*>("valueLabel");
    m_cancelledOrdersValue = m_cancelledOrdersItem->findChild<QLabel*>("valueLabel");
    m_revenueValue = m_revenueItem->findChild<QLabel*>("valueLabel");
    m_avgOrderValueValue = m_avgOrderValueItem->findChild<QLabel*>("valueLabel");
    
    // 添加到布局
    m_statsLayout->addWidget(m_totalOrdersItem);
    m_statsLayout->addWidget(m_pendingOrdersItem);
    m_statsLayout->addWidget(m_preparingOrdersItem);
    m_statsLayout->addWidget(m_completedOrdersItem);
    m_statsLayout->addWidget(m_cancelledOrdersItem);
    m_statsLayout->addWidget(m_revenueItem);
    m_statsLayout->addWidget(m_avgOrderValueItem);
}

void OrderStatisticsWidget::updateLabels(const OrderStatistics& stats)
{
    // 更新各项统计数据
    if (m_totalOrdersValue) {
        m_totalOrdersValue->setText(QString::number(stats.totalOrders));
    }
    
    if (m_pendingOrdersValue) {
        m_pendingOrdersValue->setText(QString::number(stats.pendingOrders));
    }
    
    if (m_preparingOrdersValue) {
        m_preparingOrdersValue->setText(QString::number(stats.preparingOrders));
    }
    
    if (m_completedOrdersValue) {
        m_completedOrdersValue->setText(QString::number(stats.completedOrders));
    }
    
    if (m_cancelledOrdersValue) {
        m_cancelledOrdersValue->setText(QString::number(stats.cancelledOrders));
    }
    
    if (m_revenueValue) {
        m_revenueValue->setText(formatAmount(stats.totalRevenue));
    }
    
    if (m_avgOrderValueValue) {
        m_avgOrderValueValue->setText(formatAmount(stats.averageOrderValue));
    }
    
    // 更新进度条（带动画效果）
    if (m_completionProgressBar) {
        int completionRate = calculateCompletionRate(stats.completedOrders, stats.totalOrders);
        m_targetProgress = completionRate;
        
        // 总是更新当前进度为实际显示值，并启动动画
        m_currentProgress = m_completionProgressBar->value();
        
        // 如果目标值与当前值不同，启动动画
        if (m_currentProgress != m_targetProgress) {
            if (!m_animationTimer->isActive()) {
                m_animationTimer->start();
            }
            // 如果动画正在进行中，新的目标值会在下次定时器触发时被处理
        }
        
        // 更新进度条文本
        m_completionProgressBar->setFormat(QString("%1%").arg(completionRate));
    }
}

QWidget* OrderStatisticsWidget::createStatItem(const QString& title, const QString& value, const QString& color)
{
    QWidget* container = new QWidget();
    container->setFixedSize(70, 40);
    container->setStyleSheet(STAT_ITEM_STYLE);
    
    QVBoxLayout* layout = new QVBoxLayout(container);
    layout->setContentsMargins(4, 2, 4, 2);
    layout->setSpacing(0);
    
    // 标题标签
    QLabel* titleLabel = new QLabel(title);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet(QString("color: #666666; font-size: 9px; font-weight: normal;"));
    
    // 数值标签
    QLabel* valueLabel = new QLabel(value);
    valueLabel->setObjectName("valueLabel"); // 设置对象名以便查找
    valueLabel->setAlignment(Qt::AlignCenter);
    valueLabel->setStyleSheet(QString("color: %1; font-size: 11px; font-weight: bold;").arg(color));
    
    layout->addWidget(titleLabel);
    layout->addWidget(valueLabel);
    
    return container;
}

QString OrderStatisticsWidget::formatAmount(double amount) const
{
    if (amount >= 10000) {
        return QString("¥%1万").arg(amount / 10000.0, 0, 'f', 1);
    } else if (amount >= 1000) {
        return QString("¥%1k").arg(amount / 1000.0, 0, 'f', 1);
    } else {
        return QString("¥%1").arg(amount, 0, 'f', 2);
    }
}

int OrderStatisticsWidget::calculateCompletionRate(int completed, int total) const
{
    if (total <= 0) {
        return 0;
    }
    
    return qRound((double)completed / total * 100);
}
